package com.chhuang.huaao.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.validation.ValidGroupSave;
import com.chhuang.core.validation.ValidGroupUpdate;
import com.chhuang.huaao.bean.HaMachineQueryBean;
import com.chhuang.huaao.consts.HaConstact;
import com.chhuang.huaao.po.HaCustomer;
import com.chhuang.huaao.po.HaMachine;
import com.chhuang.huaao.service.IHaCustomerService;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.huaao.thread.MachineAdminThread;
import com.chhuang.huaao.thread.MachineBinStallThread;
import com.chhuang.huaao.thread.MachineFlushTask;
import com.chhuang.huaao.thread.MachineRecoverThread;
import com.chhuang.huaao.thread.MachineStatusFlushThread;
import com.chhuang.huaao.thread.MachineTempTimeoutThread;
import com.chhuang.huaao.thread.MachineTimeIntervalThread;
import com.chhuang.huaao.thread.MachineTurnOnThread;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.system.po.ChUser;
import com.chhuang.system.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.string.Md5Util;

@Controller
@RequestMapping("/system/machine")
public class HaMachineController {
	private static final Log log = LogFactory.getLog(HaMachineController.class);

	@Autowired
	private IHaMachineService haMachineService;
	@Autowired
	private IHaCustomerService haCustomerService;
	@Autowired
	private IChUserService chUserService;
	
	/**
	 * 根据客户id获取设备的设备信息
	 * @param machineId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findMachinesByCustomerId",method=RequestMethod.POST)
	@ResponseBody
	public Object findMachinesByCustomerId(String customerId) throws Exception{
		JSONObject json = new JSONObject();
		log.debug("客户ID："+customerId);
		
		if(Assert.isValidString(customerId)){
			List<HaMachine> machines = haMachineService.findMachinesByCustomerId(customerId);
			json.put(SysConstants.Status.SUCCESS, true);
			json.put(SysConstants.Status.RESULT, machines);
//			new Thread(new MachineFlushTask(machines)).start();
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 根据设备id获取设备信息
	 * @param machineId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findMachineById",method=RequestMethod.POST)
	@ResponseBody
	public Object findMachineById(String machineId) throws Exception {
		JSONObject json = new JSONObject();
		
		log.debug("设备ID："+machineId);
		if(Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				json.put(SysConstants.Status.SUCCESS, true);
				json.put(SysConstants.Status.RESULT, machine);
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					//启动线程命令设备刷新设备信息
					new Thread(new MachineStatusFlushThread(machine)).start();
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 获取设备列表
	 * @param machineQueryBean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getList",method=RequestMethod.POST)
	@ResponseBody
	public Object getList(@RequestBody HaMachineQueryBean machineQueryBean) throws Exception{
		log.debug(machineQueryBean.getPageSize()+";"+machineQueryBean.getPageNum()
				+";"+machineQueryBean.getOrderBy()+";"+machineQueryBean.isDesc()
				+";"+machineQueryBean.isOr());
		
		QueryBean<HaMachine> queryBean = haMachineService.seniorQuery(machineQueryBean);
//		new Thread(new MachineFlushTask(queryBean.getResult())).start();
		
		return queryBean;
	}
	
	/**
	 * 添加设备信息
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/saveMachine",method=RequestMethod.POST)
	@ResponseBody
	public Object saveMachine(@RequestBody @Validated(value={ValidGroupSave.class}) HaMachine machine, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(haMachineService.findMachineByMachineNum(machine.getMachineNum())==null){
			Date now = new Date();
			machine.setCreateTime(now);
			machine.setModifyTime(now);
			machine.setCustomerId(newOrfindCustomer(machine.getCustomerId()));
			machine.setCustomerId1(newOrfindCustomer(machine.getCustomerId1()));
			machine.setCustomerId2(newOrfindCustomer(machine.getCustomerId2()));
			machine.setCustomerId3(newOrfindCustomer(machine.getCustomerId3()));
			if(haMachineService.save(machine)>0){
				json.put(HaConstact.MACHINE_ID, machine.getMachineId());
				json.put(SysConstants.Status.SUCCESS, true);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "保存设备信息失败");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备已存在");
		}
		log.debug(json.toString());
		return json;
	}

	/**
	 * 修改设备信息
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachine",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachine(@RequestBody @Validated(value={ValidGroupUpdate.class}) HaMachine machine, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				Date now = new Date();
				machineTemp.setModifyTime(now);
				machineTemp.setMachineNum(machine.getMachineNum());
				machineTemp.setMachineAname(machine.getMachineAname());
				
				machineTemp.setCustomerId(newOrfindCustomer(machine.getCustomerId()));
				machineTemp.setCustomerId1(newOrfindCustomer(machine.getCustomerId1()));
				machineTemp.setCustomerId2(newOrfindCustomer(machine.getCustomerId2()));
				machineTemp.setCustomerId3(newOrfindCustomer(machine.getCustomerId3()));
				
				if(haMachineService.update(machineTemp)>0){
					json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
					json.put(SysConstants.Status.SUCCESS, true);
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "修改设备信息失败");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 新建客户
	 * @param phone
	 * @return
	 * @throws Exception 
	 */
	private String newOrfindCustomer(String phone) throws Exception{
		if(Assert.isInvalidString(phone)){
			return null;
		}
		HaCustomer customerTemp = haCustomerService.findByCustomerAccount(phone);
		if(customerTemp==null){
			customerTemp = new HaCustomer();
			customerTemp.setCustomerAccount(phone);
			customerTemp.setCustomerPhone(phone);
			customerTemp.setCustomerPassword(Md5Util.md5(phone, phone));
			customerTemp.setLocked(false);
			Date now = new Date();
			customerTemp.setCreateTime(now);
			customerTemp.setModifyTime(now);
			haCustomerService.save(customerTemp);
		}
		return customerTemp.getCustomerId();
	}
	
	/**
	 * 删除设备信息
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/delMachines/{ids}",method=RequestMethod.DELETE)
	@ResponseBody
	public Object delMachines(@PathVariable String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] machineIds = ids.split(SysConstants.Symbol.COMMA);
			if(Assert.isValidArray(machineIds)){
				List<String> machineIdList = Arrays.asList(machineIds);
				haMachineService.deleteByPrimaryKeys(machineIdList);
				json.put(SysConstants.Status.SUCCESS, true);
			}
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
	
	/**
	 * 校验用户名密码
	 * @param userId
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/checkPassword",method=RequestMethod.POST)
	@ResponseBody
	public Object checkPassword(String userId, String password) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(userId) && Assert.isValidString(password)){
			ChUser user = chUserService.findByPrimaryKey(userId);
			if(user!=null){
				password = Md5Util.md5(password, user.getUsername());
				if(password.equals(user.getPassword())){
					json.put(SysConstants.Status.SUCCESS, true);
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "密码不正确");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "用户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "用户ID和密码不为空");
		}
		
		return json;
	}
	
	/**
	 * 修改温度与时间参数
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineTempTimeout",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineTempTimeout(@RequestBody HaMachine machine) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(machineTemp.getMachineOnlineStatus()!=null && machineTemp.getMachineOnlineStatus()==1){
					Date now = new Date();
					machineTemp.setModifyTime(now);
					
					machineTemp.setMachineTurnOffFireTemp(machine.getMachineTurnOffFireTemp());
					machineTemp.setMachineTurnOffPumpTemp(machine.getMachineTurnOffPumpTemp());
					machineTemp.setMachineTurnOnFireTemp(machine.getMachineTurnOnFireTemp());
					machineTemp.setMachineTurnOnPumpTemp(machine.getMachineTurnOnPumpTemp());
					machineTemp.setMachineTurnSmokeTemp(machine.getMachineTurnSmokeTemp());
					
					machineTemp.setMachineTurnOffBlowerTimeout(machine.getMachineTurnOffBlowerTimeout());
					machineTemp.setMachineTurnOffWindTimeout(machine.getMachineTurnOffWindTimeout());
					machineTemp.setMachineTurnOnPreFeedTimeout(machine.getMachineTurnOnPreFeedTimeout());
					machineTemp.setMachineTurnOnTimeout(machine.getMachineTurnOnTimeout());
					
					if(haMachineService.update(machineTemp)>0){
						json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
						json.put(SysConstants.Status.SUCCESS, true);
						//发送修改温度与时间参数命令
						new Thread(new MachineTempTimeoutThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改温度与时间参数失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改时间段控制参数
	 * @param machine
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editMachineTimeInterval",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineTimeInterval(@RequestBody HaMachine machine) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machine.getMachineId())){
			HaMachine machineTemp = haMachineService.findByPrimaryKey(machine.getMachineId());
			if(machineTemp!=null){
				if(machineTemp.getMachineOnlineStatus()!=null && machineTemp.getMachineOnlineStatus()==1){
					Date now = new Date();
					machineTemp.setModifyTime(now);
					
					machineTemp.setMachineWorkTimeInterval1(machine.getMachineWorkTimeInterval1());
					machineTemp.setMachineWorkTimeInterval2(machine.getMachineWorkTimeInterval2());
					machineTemp.setMachineWorkTimeInterval3(machine.getMachineWorkTimeInterval3());
					machineTemp.setMachineWorkTimeInterval4(machine.getMachineWorkTimeInterval4());
					machineTemp.setMachineWorkTimeInterval5(machine.getMachineWorkTimeInterval5());
					machineTemp.setMachineWorkTimeInterval6(machine.getMachineWorkTimeInterval6());
					machineTemp.setMachineWorkTimeInterval7(machine.getMachineWorkTimeInterval7());
					machineTemp.setMachineWorkTimeInterval8(machine.getMachineWorkTimeInterval8());
					
					if(haMachineService.update(machineTemp)>0){
						json.put(HaConstact.MACHINE_ID, machineTemp.getMachineId());
						json.put(SysConstants.Status.SUCCESS, true);
						//发送修改时间段控制参数命令
						new Thread(new MachineTimeIntervalThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改时间段控制参数失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 开机或关机
	 * @param customerId
	 * @param machineId
	 * @param turnOn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/turnOnMachine",method=RequestMethod.POST)
	@ResponseBody
	public Object turnOnMachine(String machineId, Boolean turnOn, HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();
		
		HttpSession session = request.getSession(false);
		String userId = (String) session.getAttribute(SysConstants.USER_ID);
		if(Assert.isValidString(machineId) && turnOn!=null){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					json.put(SysConstants.Status.SUCCESS, true);
					//发送开机、关机命令
					new Thread(new MachineTurnOnThread(machine, userId, turnOn)).start();
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 修改料机档位
	 * @param customerId
	 * @param machineId
	 * @param binStall
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editMachineBinStall",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineBinStall(String machineId, Integer binStall) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId) && binStall!=null){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					Date now = new Date();
					machine.setModifyTime(now);
					machine.setMachineBinStall(binStall);
					if(haMachineService.update(machine)>0){
						json.put(SysConstants.Status.SUCCESS, true);
						//发送修改料机档位命令
						new Thread(new MachineBinStallThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改料机档位失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 恢复出厂设置
	 * @param customerId
	 * @param machineId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/recoverMachine",method=RequestMethod.POST)
	@ResponseBody
	public Object recoverMachine(String machineId) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					json.put(SysConstants.Status.SUCCESS, true);
					//发送恢复出厂设置命令，恢复出厂设置后，需要返回一份最新的设备信息
					new Thread(new MachineRecoverThread()).start();
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
	
	/**
	 * 管理员修改使用期限
	 * @param machineId
	 * @param date
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/editMachineDeadline",method=RequestMethod.POST)
	@ResponseBody
	public Object editMachineDeadline(String machineId, Date date) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(machineId)){
			HaMachine machine = haMachineService.findByPrimaryKey(machineId);
			if(machine!=null){
				if(machine.getMachineOnlineStatus()!=null && machine.getMachineOnlineStatus()==1){
					Date now = new Date();
					machine.setModifyTime(now);
					machine.setMachineAdminDeadline(date);
					if(haMachineService.update(machine)>0){
						json.put(SysConstants.Status.SUCCESS, true);
						//发送管理员修改使用期限命令
						new Thread(new MachineAdminThread()).start();
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "修改料机档位失败");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "设备离线");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "设备不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "设备ID不为空");
		}
		
		return json;
	}
}
